<template>
  <div>
    <nav class="aui-navbar sql-agent-navbar"
         :class="`aui-navbar--${$store.state.navbarLayoutType}`">
      <div>
        <h1 class="aui-navbar__brand"
            @click="$router.push({ path: '/sql-agent' })">
          <a class="aui-navbar__brand-lg"
             href="javascript:;">
            <img data-v-fb5915c2=""
                 src="@/assets/mspbots/logo.png"
                 height="36"
                 alt="MSPBOTS Portal"
                 style="cursor: pointer;">
          </a>
          <a class="aui-navbar__brand-mini"
             style="fontSize:12px;"
             href="javascript:;"> <img data-v-fb5915c2=""
                 src="@/assets/mspbots/logo.png"
                 height="36"
                 alt="MSPBOTS Portal"
                 style="cursor: pointer;"></a>
        </h1>
      </div>
      <div class="aui-navbar__body menu-right-all">
        <el-menu class="aui-navbar__menu mr-auto"
                 mode="horizontal">
          <el-tooltip :open-delay="1000"
                      class="item"
                      effect="dark"
                      :content="$t('main.refresh')"
                      placement="right">
            <el-menu-item index="2"
                          id="refresh"
                          @click="refresh">
              <i class="cuifont icon_arrow_sync"
                 style="font-weight: bold;"></i>
            </el-menu-item>
          </el-tooltip>
          <el-menu-item index="77">
            <request-bundle v-if="showRequestBundleBtn && $store.state.user.tenantName !=='mspbots.ai'"></request-bundle>
          </el-menu-item>
        </el-menu>
        <el-menu class="aui-navbar__menu"
                 mode="horizontal">

          <el-menu-item index="6"
                        class="aui-navbar__avatar">
            <el-dropdown placement="bottom"
                         :show-timeout="0"
                         trigger="click">
              <span class="el-dropdown-link">
                <el-image :src="headUrl"
                          fit="cover">
                  <img slot="error"
                       fit="cover"
                       src="~@/assets/mspbots/default_avatar.png"
                       style="max-width:30px;max-height:30px;" />
                </el-image>
              </span>
              <el-dropdown-menu slot="dropdown"
                                style="width:280px;">
                <div style="display: flex;height: 80px;">
                  <div style="margin-left:16px;align-self:center;">
                    <img :src="headUrl"
                         fit="cover"
                         style="width: 50px !important;height: 50px !important;max-width: 50px !important;max-height: 50px !important;border-radius: 100%;" />
                  </div>
                  <div style="margin-top: 16px;margin-left:16px;">
                    <div style="display: flex;flex-direction:column;">
                      <span>{{ realName }}</span>
                      <span style="color: #8492a6;font-size: 13px;">{{this.$store.state.user.username}}</span>
                      <el-tooltip :open-delay="1000"
                                  effect="dark"
                                  placement="bottom">
                        <div slot="content">{{getRole(this.$store.state.user.roleList)}}</div>
                        <div style="max-width:175px;color: #8492a6;font-size: 13px; word-break: break-word;overflow: hidden;text-overflow: ellipsis; display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;">
                          {{getRole(this.$store.state.user.roleList)}}
                        </div>
                      </el-tooltip>
                    </div>
                  </div>
                </div>
                <el-dropdown-item @click.native="logoutHandle()"
                                  style="color:#E02020;"
                                  divided>{{ $t('logout') }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-menu-item>
        </el-menu>
      </div>
      <update-password v-if="updatePasswordVisible"
                       ref="updatePassowrd"></update-password>
    </nav>
  </div>
</template>

<script>
import { messages } from '@/i18n'
import screenfull from 'screenfull'
import Cookies from 'js-cookie'
import { removeToken } from '@/components/storybook/utilties/auth'
import { timeFormat } from '@/components/storybook/utilties/tools'
import { getToken } from '@/components/storybook/utilties/auth'
import { clearLoginInfo,loginSourcePathURL } from '@/utils'
import { useMsal } from '@/components/storybook/hooks/useMsal'

const { logoutPopup } = useMsal()

export default {
  data () {
    return {
      i18nMessages: messages,
      updatePasswordVisible: false,
      switchTenantVisible: false,
      messageTip: false,
      showRequestBundleBtn: true,
      notifyInstance: null
    }
  },
  computed: {
    headUrl () {
      return this.$store.state.user.headUrl ? this.$store.state.user.headUrl : this.$ossLink + '/app/other/default_avatar.png'
    },
    realName () {
      if (this.$store.state.user.realName) {
        return this.$store.state.user.realName
      } else {
      }
    }
  },
  async created () {
    this.$store.state.sidebarMenuList = window.SITE_CONFIG['menuList']
    const params1 = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 1
      }
     const {data:res} = await this.$interface.taskManager.getConnectorInfo(params1)
    // init(this.loda)
    let params = {
      secret:res.data.SQLAGENT.secret,
      token:getToken(),
      tenantCode: this.$store.state.user.tenantCode,
      tenantName: this.$store.state.user.tenantName
    }
    if(this.$store.state.user.tenantCode){
      sessionStorage.setItem('sql-tenantCode',this.$store.state.user.tenantCode)
    }else{
      params.tenantCode = sessionStorage.getItem('sql-tenantCode')
    }
    if(this.$store.state.user.tenantName){
      sessionStorage.setItem('sql-tenantName',this.$store.state.user.tenantName)
    }else{
      params.tenantName = sessionStorage.getItem('sql-tenantName')
    }
    if(!sessionStorage.getItem('refresh')) {
      const loginRes = await this.$interface.sqlAgent.login(params)
      try{
        if(!loginRes.data.seccess) {
          this.$message.error('Login failed.')
          setTimeout(async() => {
            const { userLogoutApi } = this.$interface.system
            const { data: response } = await userLogoutApi()
            removeToken()
            if (this.$store.state.user.microsoftId) {
              await logoutPopup()
            clearLoginInfo()
              sessionStorage.setItem('redirectLoginUrl', '/login?redirect=/sql-agent')
            } else {
              this.$router.push('/login?redirect=/sql-agent', () => {
                window.sessionStorage.clear()
                window.localStorage.clear()
              })
            }
          },1000)
        }
      }
      catch(err){}
    }
    
    
  },
  beforeDestroy () {
    // this.$store.state.app.WebSocket.onclose = (e) => {
    //   init(this.loda())
    //   this.$store.state.app.WebSocket = null
    // }
  },
  methods: {
    groupMergeFlag () {
      this.$store.commit('SET_UPGRADE_SQL')
    },
    refreshRequestBundle () {
      this.showRequestBundleBtn = false
      this.$nextTick(() => {
        this.showRequestBundleBtn = true
      })
    },
    loda (data) {
      this.notifyInstance && this.notifyInstance.close()

      if (data.alert && data.action && data.action === 'DEPLOY_FINISHED') {
        const time = timeFormat(data.createTime, 'HH:mm')
        this.notifyInstance = this.$notify({
          title: data.title,
          customClass: 'notify-custom',
          message: `<div>
            <div>${data.msg}</div>
            <div>${time}</div>
          </div>`,
          type: data.type,
          dangerouslyUseHTMLString: true,
          offset: 45,
          duration: 0
        })
        return
      }

      this.$store.dispatch('setDayLeft')
      if (!data) return
      this.notifyInstance = this.$notify({
        title: data.data.title,
        message: data.data.content,
        type: data.data.type,
        dangerouslyUseHTMLString: true,
        offset: 45,
        duration: 0
      })
    },
    myNoticeRouter () {
      this.$router.replace('notice-notice-user')
    },
    getUnReadCount () {
      this.$interface.system.getUnreadMessageApi().then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data > 0) {
          this.messageTip = true
        }
      }).catch(() => { })
    },
    fullscreenHandle () {
      if (!screenfull.enabled) {
        return this.$message({
          message: this.$t('fullscreen.prompt'),
          type: 'warning',
          duration: 500
        })
      }
      if (!screenfull.isFullscreen) {
        this.$store.state.sidebarFold = true
      } else {
        this.$store.state.sidebarFold = localStorage.getItem('sidebarFold') != null ? localStorage.getItem('sidebarFold') : true
      }
      screenfull.toggle()
    },
    tenantHandle () {
      this.switchTenantVisible = true
      this.$nextTick(() => {
        this.$refs.switchTenant.init()
      })
    },
    updatePasswordHandle () {
      this.updatePasswordVisible = true
      this.$nextTick(() => {
        this.$refs.updatePassowrd.init()
      })
    },

    async logoutHandle () {
      try {
        await this.$confirm(this.$t('prompt.info', { 'handle': this.$t('logout') }), this.$t('prompt.title'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        })
        await this.$interface.sqlAgent.logout()
        const { userLogoutApi } = this.$interface.system
        const { data: response } = await userLogoutApi()
        if (response.code !== 0) {
          return this.$message.error(response.msg)
        }
        removeToken()
        if(loginSourcePathURL()==='login') {
            await logoutPopup()
            clearLoginInfo()
            sessionStorage.setItem('redirectLoginUrl', '/login?redirect=/sql-agent')
        }else{
          clearLoginInfo()
            this.$router.push(`/${loginSourcePathURL()}?redirect=/sql-agent`, () => {
                this.$store.state.permission.routes = []                
            })
        }
      } catch (error) {

      }
    },
    openGetStarted () {
      this.$store.state.GetStarted.dialogStatus = true
      try {
        const hasUndoneSteps = this.$store.state.GetStarted.configList.findIndex(e => e.status === 'undone')
        if (hasUndoneSteps !== -1) {
          this.$store.state.GetStarted.steps = hasUndoneSteps
        } else {
          this.$store.state.GetStarted.steps = 0
        }
      } catch (error) { }
      setTimeout(() => {
        this.$store.state.GetStarted.dialogStatus = false
      }, 100)
    },
    getRole (roleList) {
      let arr = []
      if (roleList) {
        roleList.forEach(item => {
          arr.push(item.name)
        })
      }
      return arr.join(',')
    },
    isMe (data) {
      let temp = false
      if (data.tenantCode === this.$store.state.user.tenantCode) {
        temp = true
      }
      return temp
    },
    loginSuccess () {
      this.$interface.login.loginUserInfoApi().then(res => {
        if (res.data.code !== 0) {
          this.$store.commit('SET_API_LOAD_STATUS', false)
          return this.$message.error(res.data.msg)
        }
        this.$store.commit('SET_API_LOAD_STATUS', false)
        this.$store.commit('SET_LOGIN_USER_INFO', res.data.data)
        this.$store.state.contentTabs = window.SITE_CONFIG['routerWithForgetToken']
        window.location.reload()
        this.$router.replace({ path: '/home' })
      })
        .catch(() => {
          this.$store.commit('SET_API_LOAD_STATUS', false)
        })
    },
    setCookies (data) {
      window.location.protocol === 'https:'? Cookies.set('token', data.token, { sameSite: 'None', secure: true }) : Cookies.set('token', data.token)
      window.location.protocol === 'https:'? Cookies.set('tenant_code', data.tenantCode, { sameSite: 'None', secure: true }) : Cookies.set('tenant_code', data.tenantCode)
      sessionStorage.setItem('isMySelfCode', data.tenantCode)
      sessionStorage.setItem('isMySelfName', data.tenantName)
    },
    refresh(){
      sessionStorage.setItem('refresh',true)
      location.reload()
    }
  }
}
</script>
<style lang="scss" scoped>
.menu-right-all {
  display: flex;
  justify-content: flex-end;
}

.menu-block-css {
  width: calc(100% - 700px);
  overflow: auto;
  display: flex;
  &::-webkit-scrollbar {
    width: 10px;
    height: 0px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: skyblue;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
}
.el-image {
  max-width: 30px;
  max-height: 30px;
  width: 36px;
  height: auto;
  margin-right: 5px;
  border-radius: 100%;
  vertical-align: middle;
}
</style>

<style lang="scss">
.notify-custom {
  .el-notification__content {
    text-align: left !important;
  }
}
</style>
